use game::chess::{ChessPlayer, ChessRoom, PieceColor};

static mut ROOM_ID_INIT: u32 = 100000000;
fn new_room_id() -> u32{
    unsafe {
        if ROOM_ID_INIT > 999999998{
            ROOM_ID_INIT = 100000000;
        }
        ROOM_ID_INIT = ROOM_ID_INIT + 1;
        ROOM_ID_INIT
    }
}

pub struct Queue{
    ///前台使用的队列
    front: Vec<ChessPlayer>,

    capacity: usize,

    ///存指针
    wcursor: usize,

    ///取指针
    rcursor: usize
}

impl Queue{
    pub fn with_capacity(capacity: usize) -> Queue{
        let front = Vec::<ChessPlayer>::with_capacity(capacity);
        Queue{
            front,
            capacity,
            wcursor: 0,
            rcursor: 0
        }
    }

    ///玩家匹配的方法
    pub fn player_match(&mut self, mut white: ChessPlayer) -> Option<ChessRoom>{
        let length = self.front.len();
        if length == 0{
            info!("Put a player into match queue: {:?}", white.id());
            let message = json!({"code": 0, "status": "match"});
            white.send_message(message.to_string());
            self.push(white);
            None
        }else {
            let mut black = self.front.remove(self.rcursor);
            let mut cursor = self.rcursor + 1;
            if cursor == self.capacity{
                cursor = 0;
            }
            self.rcursor = cursor;
            white.set_color(PieceColor::White);
            let black_rep = json!({"code": 0, "turn": true, "status": "match", "opponent": white.id()});
            black.send_message(black_rep.to_string());
            let white_rep = json!({"code": 0, "turn": false, "status": "match", "opponent": black.id()});
            white.send_message(white_rep.to_string());
            let room = ChessRoom::new(new_room_id(), black, white);
            info!("Create a new room, room id = {:?}", room.id());
            Some(room)
        }
    }

    fn push(&mut self, player: ChessPlayer){
        if self.front.len() == self.capacity{
            error!("Queue is full. size: {}", self.capacity);
            return;
        }
        let cursor = self.wcursor;
        if cursor < self.capacity{
            info!("push player into queue, write cursor = {:?}, queue len = {:?}", cursor, self.front.len());
            self.front.insert(cursor,player);
            self.wcursor = cursor + 1;
        }else {
            self.front.insert(0, player);
            self.wcursor = 0;
        }
    }
}